import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class BtDatePickerWidget extends StatefulWidget {
  const BtDatePickerWidget({super.key, required this.onSelectedDate, required this.initialDate});

  final String initialDate;
  final ValueChanged<String> onSelectedDate;

  @override
  State<StatefulWidget> createState() => _BtDatePickerWidgetState();
}

class _BtDatePickerWidgetState extends State<BtDatePickerWidget> {
  DateTime _selectedDate = DateTime.now();
  String _selectedDateFormat = '';

  @override
  void initState() {
    super.initState();

    _selectedDate = widget.initialDate.isNotEmpty ? DateTime.parse(widget.initialDate) : DateTime.now();
    _selectedDateFormat = widget.initialDate.isNotEmpty ? widget.initialDate : '';
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(1900),
      lastDate: DateTime(2222),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
        _selectedDateFormat = DateFormat('yyyy-MM-dd').format(_selectedDate);
      });

      widget.onSelectedDate(_selectedDateFormat);
    }
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
        onPressed: () => _selectDate(context),
        child: Text(_selectedDateFormat, style: const TextStyle(fontSize: 16, color: Color(0xFF404040))));
  }
}
